package com.sh.web.controller;


import com.sh.bean.CartItem;
import com.sh.bean.Resorder;
import com.sh.bean.Resuser;
import com.sh.service.ResorderBiz;
import com.sh.web.models.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/resorder")
public class ResorderController {
    @Autowired
    private ResorderBiz resorderBiz;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping(value = "/confirmOrder", method = RequestMethod.POST)
    public ResponseResult confirmOrder(@RequestBody Resorder resorder, HttpServletRequest request) {
        Map<String, Object> userClaims = (Map<String, Object>) request.getAttribute("userClaims");
        String userid = userClaims.get("userid").toString();
        if (!redisTemplate.hasKey("cart:" + userid)) {
            return ResponseResult.error("购物车为空");
        }
        Map<String, CartItem> cart = (Map<String, CartItem>) redisTemplate.opsForValue().get("cart:" + userid);
        resorder.setUserid(Integer.valueOf(userid));
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        resorder.setOrdertime(df.format(now));  // 订单时间

        // 送货时间的设置
        if (resorder.getDeliverytime() == null || "".equals(resorder.getDeliverytime())) {
            LocalDateTime deliveryTime = now.plusHours(1);  // 默认1小时送达
            resorder.setDeliverytime(df.format(deliveryTime));
        }
        resorder.setStatus(0);
        try {
            Resuser resuser = Resuser.builder().userid(Integer.valueOf(userid)).build();
            resorderBiz.order(resorder, new HashSet<>(cart.values()), resuser);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("下单失败");
        }
        redisTemplate.delete("cart:" + userid);  // 删除购物车的redis
        return ResponseResult.ok("下单成功");
    }


    @GetMapping("/payAction/{flag}")
    public Map<String, Object> payAction(@PathVariable Integer flag) throws InterruptedException {
        log.info("flag:{}", flag);
        if (flag == 2) {
            Thread.sleep(1000);
            return Map.of("status", "fail");
        }else if ( flag==3 ){
            throw new RuntimeException("支付失败");
        }
        return Map.of("status", "success");
    }


}
